package supercafe.core;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import supercafe.dataprovider.DataPoster;
import supercafe.dataprovider.DataGetter;
import supercafe.dataprovider.FinishGet;
import supercafe.dataprovider.FinishPost;
import supercafe.defines.IntentAction;
import supercafe.defines.URLs;
import supercafe.more.MainScreen;
import supercafe.more.Profile;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class MakeOrderDetailsScreen extends ListActivity implements FinishGet, FinishPost, OnItemSelectedListener, OnClickListener, android.content.DialogInterface.OnClickListener {

	protected Hashtable<Integer,MenuType> listMenuTypes_Items = null;
	protected Vector<MenuType> listMenuTypes = null;
	protected ArrayList<String> menuTypeNames = null;
	protected int menuPosition = 0;//position of menu type
	protected DataGetter dataGetter = new DataGetter(this,this);
	protected DataPoster dataPoster = new DataPoster(this,this);
	protected Spinner spinnerMenuTypes = null;
	
	protected Vector<OrderItem> listItems;
	protected OrderItemAdapter adap;
	
	protected ProgressDialog m_ProgressDialog_getMenus = null;
	
	protected int tableId;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        tableId = this.getIntent().getIntExtra("tableId", -1);
        
        setContentView(R.layout.make_order_details_screen);
        listMenuTypes = new Vector<MenuType>();
        listItems = new Vector<OrderItem>();
        Runnable getMenuItemsRunnable = new Runnable(){
            @Override
            public void run() {
            	getAllMenus();            	
            }
        };
        Thread thread =  new Thread(null, getMenuItemsRunnable, "GetMenuItems-MagentoBackground");
        thread.start();
        
        listMenuTypes_Items = new Hashtable<Integer,MenuType>();
        
        Button btnGoMenu = (Button) findViewById(R.id.btnGoMenu);
        btnGoMenu.setOnClickListener(this);
        Button btnBack = (Button) findViewById(R.id.btnCancel);
        btnBack.setOnClickListener(this);
        Button btnSubmitNewOrder = (Button) findViewById(R.id.btnSubmit);
        btnSubmitNewOrder.setOnClickListener(this);
        Button btnClearAll = (Button) findViewById(R.id.btnClearAll);
        btnClearAll.setOnClickListener(this);
        
        adap = new OrderItemAdapter(this, R.layout.list_order_items_row, listItems);
        setListAdapter(adap);
    }
    
    protected void showMenuSpinner() {
		// TODO Auto-generated method stub
    	menuTypeNames = new ArrayList<String>();
        for(int i=0;i<listMenuTypes.size();i++){
        	//listMenuTypes.put(allMenus.get(i), allMenus.get(i).getTypeId());
        	menuTypeNames.add(listMenuTypes.get(i).getTypeName());
        	listMenuTypes_Items.put(listMenuTypes.get(i).getTypeId(),listMenuTypes.get(i));
        }
        
        //init Spinner
        spinnerMenuTypes = (Spinner) findViewById(R.id.spinnerMenuTypes);
        spinnerMenuTypes.setOnItemSelectedListener(this);
        ArrayAdapter<String> aa = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, menuTypeNames);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        spinnerMenuTypes.setAdapter(aa);
	}

    protected Runnable showMenuSpinnerRunnable = new Runnable() {
    	@Override
        public void run() {
            showMenuSpinner();
        }
    };
	private String requestResult;
    
    protected void getAllMenus() {
		// TODO Auto-generated method stub
    	//AllMenus.requestMenus(this, "http://192.168.1.53/admin/types/retrieve");
    	listMenuTypes = AllMenus.getMenus(this);        
		runOnUiThread(showMenuSpinnerRunnable);
	}

	public void onItemSelected(AdapterView<?> unUsedAdapter, View unUsedView, int position,
			long id) {
    	//spinner menu types listener
    	try{
    		this.menuPosition = position;
    		//Toast.makeText(this, "Bạn đã chọn Thực Đơn: "+menuTypeNames.get(position), 3000).show();
    	}catch(Exception e){
    		Log.e("exception-tag",e.getMessage());
    	}
	}

	public void onNothingSelected(AdapterView<?> arg0) {}
	
	public void onClick(View v) {
		// TODO Auto-generated method stub
		//go to appreciated menu
    	try{
    		int id = v.getId();
    		switch(id){
    			case R.id.btnGoMenu:
		    		Intent goMenuIntent = new Intent(this, 
		    				//MenuItemsScreen.class);
		    				MenuItemsScreen2.class);
		    		goMenuIntent.putExtra("menu",(listMenuTypes.get(menuPosition)));
					startActivityForResult(goMenuIntent, IntentAction.GET_MENU_ACTION);
					break;
    			case R.id.btnClearAll:
    				if(listItems.isEmpty()) return;
    				//Toast.makeText(this, "btnClearAll", 3000).show();
    				AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setMessage("Bạn chắc chắn muốn xóa hết đơn hàng này?")
					       .setCancelable(false)
					       .setPositiveButton("Có", new DialogInterface.OnClickListener() {
					    	   
					           public void onClick(DialogInterface dialog, int id) {
					                MakeOrderDetailsScreen.this.clearCurrentOrder();
					           }
					       })
					       .setNegativeButton("Không", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					                dialog.cancel();
					           }
					       });
					AlertDialog alert = builder.create();
					alert.show();
    				break;
    			case R.id.btnCancel:
    				/*
    				//Toast.makeText(this, "btnCancel", 3000).show();
    				builder = new AlertDialog.Builder(this);
					builder.setMessage("Bạn chắc chắn muốn trở về?")
					       .setCancelable(false)
					       .setPositiveButton("Có", new DialogInterface.OnClickListener() {
					    	   
					           public void onClick(DialogInterface dialog, int id) {
					        	   Intent returnToTaskScreenIntent = new Intent();
					        	   //returnToTaskScreenIntent.putExtra("key", "value");
					               setResult(Activity.RESULT_CANCELED, returnToTaskScreenIntent);
					        	   MakeOrderDetailsScreen.this.finish();
					           }
					       })
					       .setNegativeButton("Không", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					                dialog.cancel();
					           }
					       });
					alert = builder.create();
					alert.show();
					*/
    				Intent returnToTaskScreenIntent = new Intent();
    				setResult(Activity.RESULT_CANCELED, returnToTaskScreenIntent);
    				MakeOrderDetailsScreen.this.finish();
    				break;
    			case R.id.btnSubmit:
    				if(listItems.isEmpty()) return;
    				//Toast.makeText(this, "btnSubmit", 3000).show();
    				builder = new AlertDialog.Builder(this);
					builder.setMessage("Bạn chắc chắn muốn đặt đơn hàng này?")
					       .setCancelable(false)
					       .setPositiveButton("Có", this)
					       .setNegativeButton("Không", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					                dialog.cancel();
					           }
					       });
					alert = builder.create();
					alert.show();
    				break;
    		}
    	}catch(Exception e){
    		Log.e("exception-tag",e.getMessage());
    	}
	}
	
	protected void clearCurrentOrder() {
		// TODO Auto-generated method stub
		this.listItems.removeAllElements();
		this.adap.notifyDataSetChanged();
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
        switch (requestCode) {
            case IntentAction.EDIT_NOTE_ACTION:
                try {
                	if(resultCode==Activity.RESULT_OK){
	                    String value = data.getStringExtra("note");
	                    if (value != null && value.length() > 0) {
	                        //do something with value
	                    	this.adap.setNoteToCurrentItemLine(value);
	                    	this.adap.notifyDataSetChanged();
	                    }
                	}
                } catch (Exception e) {
                }
                break;
            case IntentAction.GET_MENU_ACTION:
                try {
                	if(resultCode==Activity.RESULT_OK){
	                    Bundle receiveData = data.getExtras();
	                    if (!receiveData.isEmpty()) {
	                        //do something with value
	                    	int menuTypeId = receiveData.getInt("menuTypeId");
	                    	ArrayList<Integer> moreItemIds = receiveData.getIntegerArrayList("itemIDs");
	                    	moreItemIds = reduceDuplicatedItems(moreItemIds);
	                    	addMoreItems(menuTypeId, moreItemIds);
	                    	//this.adap.addItems(value);
	                    }
                	}
                } catch (Exception e) {
                }
                break;
            default:
                break;
        }
    }

	protected void addMoreItems(int menuTypeId, ArrayList<Integer> moreItemIds) {
		// TODO Auto-generated method stub
		//get item info from item IDs
		MenuType menuType = listMenuTypes_Items.get(menuTypeId);
		List<MenuItem> items = menuType.getMenuItems();
		//add new item lines
		int lenMenuItem = items.size();
		int lenMoreItem = moreItemIds.size();
		for(int i_menuItem=0;i_menuItem<lenMenuItem;i_menuItem++){
			for(int i_item=0;i_item<lenMoreItem;i_item++){
				int id = items.get(i_menuItem).getMenuItemId();
				if(moreItemIds.get(i_item)==id){
					String itemName = items.get(i_menuItem).getMenuItemName();
					int price = items.get(i_menuItem).getMenuItemPrice();
					listItems.add(new OrderItem(id,itemName,1,price,""));
					break;
				}
			}
		}
		adap.notifyDataSetChanged();
	}

	protected ArrayList<Integer> reduceDuplicatedItems(
			ArrayList<Integer> moreItemIds) {
		// TODO Auto-generated method stub
		//reduce all duplicated item within current list items
		int len = this.listItems.size();
		int moreLen = moreItemIds.size();
		for(int i=0;i<len;i++) {
			for(int j=0;j<moreLen;j++){
				if(this.listItems.get(i).getItemId()==moreItemIds.get(j)){
					moreItemIds.remove(j);
					moreLen--;
				}
			}
		}
		return moreItemIds;
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		// TODO Auto-generated method stub
		// submit new order
		Log.i("@nhan","click on dialog submit");
		String xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
		    	"<order>"+
				"<employee>"+Profile.employeeId+"</employee>"+
				"<table>"+tableId+"</table>";
		xml += "<items>";
		for(int i=0;i<this.listItems.size();i++){			
				xml += "<item id=\""+this.listItems.get(i).getItemId()+"\">"+
						"<quanlity>"+this.listItems.get(i).getQuanlity()+"</quanlity>"+
						"<note>"+this.listItems.get(i).getNote()+"</note>"+
						"</item>";
		}
		xml += "</items></order>";
		//Toast.makeText(this, xml, Toast.LENGTH_LONG).show();
		//dataPoster = new DataPoster(this,this);
		dataPoster.execute(xml,URLs.POST_NEW_ORDER,"orderXml");
		/*
		while(!dataPoster.isFinished()){
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		doFinishPost();
		*/
	}

	@Override
	public void doFinishGet() {
		// TODO Auto-generated method stub
		Toast.makeText(this, "doFinishGet in make order details screen", Toast.LENGTH_LONG).show();
	}

	@Override
	public void doFinishPost() {
		// TODO Auto-generated method stub
		//posting order finished
		String resultXML = dataPoster.getResponseResult();
		requestResult = XMLHandler.getMessage(resultXML);
		if(requestResult==null){
			requestResult = "Đã đặt đơn hàng thành công";
			// chuyển qua activity MainScreen
			Toast.makeText(this, requestResult, Toast.LENGTH_LONG).show();
			Intent mainScreen = new Intent(this, MainScreen.class);
			startActivity(mainScreen);
			finish();
			return ;
		}
		Toast.makeText(this, requestResult, Toast.LENGTH_LONG).show();
	}	
}